<template>
  <div class="repair-workbench animate__animated animate__fadeIn">
    <div class="welcome-banner">
      <div class="banner-content">
        <i class="el-icon-s-tools banner-icon"></i>
        <div class="banner-text">
          <h2>电脑维修工作台</h2>
          <p>欢迎回来，{{ user.realName }}！今天也要继续努力维修哦~</p>
        </div>
      </div>
      
      <div class="repair-stats">
        <el-row :gutter="24">
          <el-col :span="6" v-for="(item, index) in statsItems" :key="index">
            <div class="stat-card" :class="`stat-${item.type}`">
              <div class="stat-icon">
                <i :class="item.icon"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value counter">{{ stats[item.key] }}</div>
                <div class="stat-label">{{ item.label }}</div>
              </div>
              <div class="stat-wave"></div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="task-list-container animate__animated animate__fadeInUp">
      <div class="section-header">
        <div class="header-left">
          <h3>维修任务管理</h3>
          <span class="subtitle">共 {{ total }} 条记录</span>
        </div>
        <el-radio-group v-model="listType" size="medium">
          <el-radio-button label="pending">
            <i class="el-icon-time"></i> 待接单
          </el-radio-button>
          <el-radio-button label="processing">
            <i class="el-icon-loading"></i> 处理中
          </el-radio-button>
          <el-radio-button label="completed">
            <i class="el-icon-circle-check"></i> 已完成
          </el-radio-button>
        </el-radio-group>
      </div>

      <el-table
        :data="taskList"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        v-loading="loading"
        border>
        <el-table-column prop="rId" label="任务编号" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="showTaskDetail(scope.row)">
              #{{ scope.row.rId }}
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="userName" label="报修人" width="120" align="center">
          <template slot-scope="scope">
            <el-tag size="medium" effect="plain" type="info">
              {{ scope.row.userName || '加载中...' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="故障图片" width="120" align="center">
          <template slot-scope="scope">
            <el-image 
              style="width: 80px; height: 80px; border-radius: 4px;"
              :src="scope.row.imgUrl"
              fit="cover"
              :preview-src-list="[scope.row.imgUrl]">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        
        <el-table-column prop="reason" label="故障描述" min-width="200" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <span class="reason-text">{{ scope.row.reason }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="userDorm" label="宿舍号" width="120" align="center">
          <template slot-scope="scope">
            <el-tag size="medium" effect="plain" type="success">
              {{ scope.row.userDorm }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="phone" label="联系方式" width="140" align="center">
          <template slot-scope="scope">
            <el-tag size="medium" effect="plain" type="warning">
              {{ scope.row.phone }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column 
          prop="repairerName" 
          label="维修员" 
          width="120" 
          align="center">
          <template slot-scope="scope">
            <el-tag 
              v-if="scope.row.bmUserId"
              size="medium" 
              effect="plain" 
              type="primary">
              {{ scope.row.repairerName || '加载中...' }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="remark" label="维修备注" width="180" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
            <span v-else class="no-remark">暂无备注</span>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              effect="dark"
              size="medium">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column v-if="listType !== 'completed'" label="操作" width="120" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="primary"
              size="small"
              icon="el-icon-check"
              @click="acceptTask(scope.row)">
              接单
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="success"
              size="small"
              icon="el-icon-finished"
              @click="showCompleteDialog(scope.row)">
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total"
          background>
        </el-pagination>
      </div>
    </div>

    <!-- 完成任务对话框 -->
    <el-dialog
      title="完成维修任务"
      :visible.sync="completeDialogVisible"
      width="30%"
      custom-class="complete-dialog">
      <div class="dialog-content">
        <div class="task-info">
          <p>任务编号：#{{ currentTask?.rId }}</p>
          <p>报修人：{{ currentTask?.userName }}</p>
        </div>
        <el-form :model="completeForm" label-width="80px">
          <el-form-item label="维修备注" required>
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入维修过程和结果说明"
              v-model="completeForm.remark">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="completeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="completeTask">确认完成</el-button>
      </span>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog
      title="维修任务详情"
      :visible.sync="dialogVisible"
      width="50%">
      <div v-if="currentTask" class="task-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报修人">{{ currentTask.userName || '未知用户' }}</el-descriptions-item>
          <el-descriptions-item label="电脑类型">{{ currentTask.pcType === '1' ? '笔记本' : '台式电脑' }}</el-descriptions-item>
          <el-descriptions-item label="电脑品牌">{{ currentTask.pcName }}</el-descriptions-item>
          <el-descriptions-item label="联系方式">{{ currentTask.phone }}</el-descriptions-item>
          <el-descriptions-item label="宿舍号">{{ currentTask.userDorm }}</el-descriptions-item>
          <el-descriptions-item label="故障描述">{{ currentTask.reason }}</el-descriptions-item>
        </el-descriptions>
        <div class="detail-image">
          <p>故障图片：</p>
          <el-image 
            style="width: 200px; height: 200px"
            :src="currentTask.imgUrl"
            fit="cover"
            :preview-src-list="[currentTask.imgUrl]">
          </el-image>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="acceptTask(currentTask)" 
          v-if="currentTask && currentTask.status === 0">
          接单
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RepairWorkbench',
  data() {
    return {
      loading: false,
      statsItems: [
        { key: 'pending', label: '待接单', type: 'warning', icon: 'el-icon-time' },
        { key: 'processing', label: '处理中', type: 'primary', icon: 'el-icon-loading' },
        { key: 'completed', label: '已完成', type: 'success', icon: 'el-icon-check' },
        { key: 'rating', label: '平均评分', type: 'info', icon: 'el-icon-star-on' }
      ],
      stats: {
        pending: 0,
        processing: 0,
        completed: 0,
        rating: 0
      },
      listType: 'pending',
      taskList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      completeDialogVisible: false,
      currentTask: null,
      completeForm: {
        remark: ''
      },
      user: JSON.parse(localStorage.getItem('xm-user') || '{}')
    }
  },
  methods: {
    loadStats() {
      // 由于后端暂无统计接口，先用selectPage接口统计不同状态的数量
      const params = {
        pageNum: 1,
        pageSize: 999 // 获取所有数据进行统计
      }
      this.$request.get('/repairInfo/selectPage', { params }).then(res => {
        if (res.code === '200') {
          const list = res.data.list || []
          this.stats = {
            pending: list.filter(item => item.status === 0).length,
            processing: list.filter(item => item.status === 1).length,
            completed: list.filter(item => item.status === 2).length,
            rating: 0 // 暂无评分功能
          }
        }
      })
    },
    loadTasks() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        status: this.listType === 'pending' ? 0 : this.listType === 'processing' ? 1 : 2
      }
      this.$request.get('/repairInfo/selectPage', { params }).then(res => {
        if (res.code === '200') {
          this.taskList = res.data.list.map(task => ({
            ...task,
            rId: task.rId ? task.rId.toString() : null
          }))
          this.total = res.data.total
          
          // 获取每个任务的报修人姓名和维修员姓名
          this.taskList.forEach(task => {
            this.loadUserName(task)
            if (task.bmUserId) {
              this.loadRepairerName(task)
            }
          })
        }
      })
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadTasks()
    },
    showTaskDetail(task) {
      if (task.userId && !task.userName) {
        this.loadUserName(task)
      }
      // 确保当前任务的 rId 是数字类型
      task.rId = parseInt(task.rId)
      this.currentTask = task
      this.dialogVisible = true
    },
    acceptTask(task) {
      this.$confirm('确认接受此维修任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const updateData = {
          status: 1,
          bmUserId: this.user.id,
          bmRealName: this.user.realName
        }
        
        // 使用 URL 参数传递 rid
        this.$request.post(`/repairInfo/updateStatus?rid=${task.rId}`, updateData).then(res => {
          if (res.code === '200') {
            this.$message.success('接单成功')
            this.dialogVisible = false
            this.loadTasks()
            this.loadStats()
          } else {
            this.$message.error(res.msg || '接单失败')
          }
        })
      }).catch(() => {
        this.$message.info('已取消接单')
      })
    },
    showCompleteDialog(task) {
      this.currentTask = task
      this.completeForm.remark = ''
      this.completeDialogVisible = true
    },
    completeTask() {
      if (!this.completeForm.remark) {
        this.$message.warning('请输入维修备注')
        return
      }

      const updateData = {
        status: 2,
        remark: this.completeForm.remark,
        bmUserId: this.user.id // 添加维修员ID
      }

      this.$request.post(`/repairInfo/updateStatus?rid=${this.currentTask.rId}`, updateData).then(res => {
        if (res.code === '200') {
          this.$message.success('任务已完成')
          this.completeDialogVisible = false
          this.loadTasks()
          this.loadStats()
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      })
    },
    getStatusType(status) {
      return {
        0: 'warning',   // 待接单
        1: 'primary',   // 处理中
        2: 'success',   // 已完成
      }[status] || 'info'
    },
    getStatusText(status) {
      return {
        0: '待接单',
        1: '处理中',
        2: '已完成',
      }[status] || '未知'
    },
    tableRowClassName({row}) {
      if (row.status === 0) return 'pending-row'
      if (row.status === 1) return 'processing-row'
      return ''
    },
    loadUserName(task) {
      if (task.userId) {
        this.$request.get(`/userInfo/selectById/${task.userId}`).then(res => {
          if (res.code === '200' && res.data) {
            const userName = res.data.realName || '未知用户'
            this.$set(task, 'userName', userName)
          } else {
            this.$set(task, 'userName', '未知用户')
          }
        }).catch(() => {
          this.$set(task, 'userName', '未知用户')
        })
      } else {
        this.$set(task, 'userName', '未知用户')
      }
    },
    loadRepairerName(task) {
      if (task.bmUserId) {
        this.$request.get(`/userInfo/selectById/${task.bmUserId}`).then(res => {
          if (res.code === '200' && res.data) {
            this.$set(task, 'repairerName', res.data.realName)
          }
        })
      }
    },
    initCounterAnimation() {
      const counters = document.querySelectorAll('.counter');
      counters.forEach(counter => {
        const target = parseInt(counter.innerText);
        let count = 0;
        const speed = 2000 / target;
        
        const updateCount = () => {
          if(count < target) {
            count++;
            counter.innerText = count;
            setTimeout(updateCount, speed);
          }
        };
        
        updateCount();
      });
    }
  },
  created() {
    this.loadStats()
    this.loadTasks()
  },
  watch: {
    listType() {
      this.currentPage = 1
      this.loadTasks()
    }
  },
  mounted() {
    this.initCounterAnimation();
  }
}
</script>

<style scoped>
/* 删除这行 */
/* @import 'animate.css'; */

.repair-workbench {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  min-height: calc(100vh - 48px);
}

.welcome-banner {
  background: white;
  padding: 32px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,21,41,.08);
  margin-bottom: 24px;
}

.banner-content {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
}

.banner-icon {
  font-size: 48px;
  color: #409EFF;
  margin-right: 24px;
  padding: 20px;
  background: #ecf5ff;
  border-radius: 12px;
}

.banner-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.banner-text p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.repair-stats {
  margin-top: 24px;
}

.stat-card {
  position: relative;
  background: white;
  padding: 24px;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0,21,41,.12);
}

.stat-wave {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40%;
  background: linear-gradient(45deg, rgba(64,158,255,0.1), rgba(103,194,58,0.1));
  clip-path: polygon(0 100%, 100% 70%, 100% 100%, 0% 100%);
}

.stat-icon {
  position: relative;
  z-index: 1;
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  transition: all 0.3s;
}

.stat-card:hover .stat-icon {
  transform: scale(1.1) rotate(10deg);
}

.stat-value {
  position: relative;
  z-index: 1;
  font-size: 32px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  position: relative;
  z-index: 1;
  font-size: 14px;
  color: #909399;
}

.task-list-container {
  background: white;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,21,41,.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: baseline;
}

.header-left h3 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  margin-right: 12px;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.complete-dialog .dialog-content {
  padding: 20px 0;
}

.task-info {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.task-info p {
  margin: 8px 0;
  color: #606266;
}

.pagination-container {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .repair-workbench {
    padding: 16px;
  }
  
  .welcome-banner {
    padding: 20px;
  }
  
  .banner-content {
    flex-direction: column;
    text-align: center;
  }
  
  .banner-icon {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .repair-stats .el-col {
    margin-bottom: 16px;
  }
}

/* 添加过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.reason-text {
  color: #606266;
  line-height: 1.5;
}

.no-remark {
  color: #909399;
  font-size: 13px;
}

.el-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.el-table::before {
  display: none;
}

.el-table th {
  background: #f5f7fa !important;
  color: #303133;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-table .el-button--text {
  font-weight: 600;
}

.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

.el-image {
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.el-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px 0 rgba(0,0,0,0.15);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.el-button {
  padding: 9px 15px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.el-button [class*="el-icon-"] + span {
  margin-left: 6px;
}

/* 状态标签的特殊样式 */
.el-tag.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

.el-tag.el-tag--primary {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.el-tag.el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}
</style> 